import os
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import ddddocr

# 当前文件所在的文件夹路径
current_path = os.path.abspath(os.path.dirname(__file__))
# chrome浏览器路径
chrome_location = os.path.join(current_path, 'chrome-win')
# chrome.exe完整路径
browser_location = os.path.join(chrome_location, 'chrome.exe')
# chromedriver.exe的完整路径
driver_location = os.path.join(chrome_location, 'chromedriver.exe')
# 创建一个Servic对象，传入ChromeDriver的路径
service = Service(driver_location)
# 创建Chrome选项
options =  Options()
options.binary_location = browser_location
# 不显示 Chrom正受到自动测试软件控制
options.add_experimental_option("excludeSwitches", ['enable-automation'])
# 禁用自动化控制特性，避免被网站检测到
# window.navigator.webdriver属性设置为: false
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument(
    'User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
    'Chrome/128.0.0.0 Safari/537.36')
driver = webdriver.Chrome(service=service,options=options)
wait = WebDriverWait(driver, 5, poll_frequency=0.5)
ocr = ddddocr.DdddOcr()
# 判断验证码是否存在,是否需要验证
def is_required_verify():
    result=False
    try:
        tips_xpath='//*[@class="dealCodeInfo"][1]'
        wait_result = wait.until(lambda x: x.find_elements(By.XPATH,tips_xpath).__len__() > 0)
        result=driver.find_element(By.XPATH, tips_xpath).text.strip()=="请完成上方验证码操作"
    except Exception as e:
        print(e)
    finally:
        return result
# 输入验证码
def input_code():
    # 验证码元素的xpath
    img_xpath = '//*[@id="code_img"]'
    verify_code = None
    wait_result=False
    try:
        # 判断文件夹是否存在，若不存在则创建
        img_dir = os.path.join(current_path, "img")
        # 判断文件夹是否存在，若不存在则创建
        if not os.path.exists(img_dir):
            os.makedirs(img_dir)
        # 验证码图片完整路径
        img_full_path = os.path.join(img_dir, "verify.jfif")
        wait_result = wait.until(lambda x: x.find_elements(By.XPATH, img_xpath).__len__() > 0)
        # 验证码会变，该方式不行 img_url = driver.find_element(By.XPATH, img_xpath).get_attribute('src')
        img_ele= driver.find_element(By.XPATH, img_xpath)
        # 截图
        img_ele.screenshot(img_full_path)
        with open(img_full_path, "rb") as f:
            # 读取截图图片
            image = f.read()
            # ocr识别结果
            result = ocr.classification(image)
            print(result)
            verify_code = result
    except Exception as e:
        print(e)
    if verify_code:
        try:
            # 验证输入框xpath     //*[@id="verifycode"]
            input_xpath = '//*[@id="verifycode"]'
            wait_result = wait.until(lambda x: x.find_elements(By.XPATH, input_xpath).__len__() > 0)
            input_ele=driver.find_element(By.XPATH, input_xpath)
            #验证码文本框输入验证码
            input_ele.send_keys(verify_code)
        except Exception as e:
            print(e)
# 点击查询
def click_select():
    # 点击查询
    click_xpath = '//button[@class="el-button el-button--primary el-button--medium"]/span'
    click_ele = driver.find_element(By.XPATH, click_xpath)
    driver.execute_script("arguments[0].click()", click_ele)
if __name__ == '__main__':
    try:
        url = "https://hljcg.hlj.gov.cn/maincms-web/noticeInformationHlj?typeId=ggxx"
        driver.get(url)
        # 是否需要验证
        is_verify=is_required_verify()
        if is_verify:
            input_code()
            click_select()
    except Exception as e:
        print(e)
    finally:
        driver.quit()







